package app

import (
	"fmt"
	"log"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/cio"
	"github.com/urfave/cli/v2"
)

var StopCommand = &cli.Command{
	Name:      "stop",
	Usage:     "stop one or more container",
	ArgsUsage: "CONTAINER [CONTAINER, ...]",
	Flags:     []cli.Flag{},
	Action: func(context *cli.Context) error {
		client, ctx, cancel, err := NewClient(context)
		if err != nil {
			return err
		}
		defer cancel()

		if context.NArg() == 0 {
			return fmt.Errorf("must specify at least one container to stop")
		}

		var opts []containerd.ProcessDeleteOpts
		opts = append(opts, containerd.WithProcessKill)
		for _, id := range context.Args().Slice() {
			// force delete task
			container, err := client.LoadContainer(ctx, id)
			if err != nil {
				log.Fatal(err)
				continue
			}
			task, err := container.Task(ctx, cio.Load)
			if err != nil {
				log.Fatal(err)
				continue
			}
			status, err := task.Delete(ctx, opts...)
			if err != nil {
				log.Fatal(err)
				continue
			}
			if ec := status.ExitCode(); ec != 0 {
				log.Println(id)
			}
		}

		return nil
	},
}
